package com.kingtone.rongji.wxapi;

import com.kingtone.rongji.R;
import com.kingtone.rongji.pay.weixin.Constants;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.RongJiUtils;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{
	
	private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";
	private Context mContext = null;
    private IWXAPI api;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weixin_pay_result);
    	api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);

        api.handleIntent(getIntent(), this);
        mContext = WXPayEntryActivity.this;
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
        api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		
		RongJiUtils.dismissProgress();
		if(resp != null)
		{
			int errorCode = resp.errCode;
			Log.d(TAG, "onPayFinish, errCode = " + errorCode);

			if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.app_name);
				builder.setPositiveButton(R.string.pay_result_btn_confirm, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(final DialogInterface dialog, final int which) {
						dialog.cancel();
						finish();
						Intent inconIntent=new Intent();  
				        inconIntent.setAction(AppContasts.BROADCAST_ACTION_CLOSE_ACTIVITY);  
				        mContext.sendBroadcast(inconIntent);
					}
				});
				String resultStr = "";
				if(errorCode == 0)
				{
					resultStr = getString(R.string.pay_result_ok);
				}else if(errorCode == -2)
				{
					resultStr = getString(R.string.pay_result_cancel);
				}else
				{
					resultStr = getString(R.string.pay_result_failure);
				}
				builder.setMessage(getString(R.string.pay_result_callback_msg, resultStr));
				builder.show();
			}
		}
	}
}